/*
 * @Date: 2023-03-04 20:04:52
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-05 10:24:30
 * @FilePath: \A19\backend\src\api\SourceManage\ApiNewFolder.ts
 */
import { ApiCall } from "tsrpc";
import { ReqNewFolder, ResNewFolder } from "../../shared/protocols/SourceManage/PtlNewFolder";
import { Global } from "../../Global";
import { folders } from '../../shared/types/Folder';
import { findFolder } from '../../utils/FindCurrentFolder';

export default async function (call: ApiCall<ReqNewFolder, ResNewFolder>) {
    // TODO
    const course = call.req.course
    const root = await Global.collection('folders').findOne({
        course
    })
    if(!root) return call.error('课程不存在')

    const folder = findFolder(call.req.path,root)
    if(!folder) return call.error('文件夹创建失败')

    if(folder.folders.find(f => f.name === call.req.name)) return call.error('文件夹已存在')
    folder.folders.push({
        files:[],
        folders:[],
        name:call.req.name,
        course
    })
    // console.log(root);
    
    await Global.collection('folders').updateOne({
        course
    },{
        $set:{
            folders:root.folders
        }
    })

    // const ret = await Global.collection('folders').updateOne({
    //     course,
    // },{
        
    // })
    // console.log(ret);
    console.log(folder);
    call.succ({
        files:folder.files,
        folders:folder.folders.map(f => f.name)
    })
}